import type { ProFormInstance } from '@/components/Pro/';
import {
  ProForm,
  ProFormCheckbox,
  ProFormDatePicker,
  ProFormDigit,
  ProFormRadio,
  ProFormSelect,
  ProFormText,
} from '@/components/Pro/';
import Tabs, { TabsProps } from '@/components/Tabs';
import {
  CAPACITY_UNIT,
  getPvGridConnectedMode,
  getSystemElectricityPriceType,
  PHO_UNIT,
  PIE_UNIT,
  POWER_UNIT,
} from '@/dictionary';
import { stationControllerSaveBaseConfig as edit } from '@/services/ess/station';
import { useIntl } from '@umijs/max';
import { Button, Flex, message, Space, Typography } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { useAccess } from 'umi';
import Styles from '../index.less';
import MapComponent from './Bmap';
import Device, { ToolBarRender as DeviceToolBarRender } from './Device';
import ElectricityPrice, { ToolBarRender } from './ElectricityPrice';
import TempCollectePoint from './TempCollectePoint';
const { Title } = Typography;

const BaseParam: React.FC<{
  detailInfo?: API.StationInfo;
  disableEdit?: boolean;
}> = ({ detailInfo, disableEdit }) => {
  const formRef = useRef<ProFormInstance>();
  const WIDTH = 450;
  const LABEL_WIDTH = 160;
  const GAP = 10;
  const pointString =
    detailInfo?.point && detailInfo.point.lng !== null && detailInfo.point.lat !== null
      ? `${detailInfo.point.lng}, ${detailInfo.point.lat}`
      : null;
  useEffect(() => {
    formRef?.current?.setFieldsValue({
      ...detailInfo,
      cellConnect: detailInfo?.cellConnect?.toString(),
      capacityUnit: detailInfo?.capacityUnit || 'MWh',
      ratedPowerUnit: detailInfo?.ratedPowerUnit || 'MW',
      chargeDischargeUnit: detailInfo?.chargeDischargeUnit || 'H',
      point: pointString,
      energyComplex: detailInfo?.energyComplex || {},
      priceType: detailInfo?.priceType?.toString(),
    });
  }, [detailInfo]);

  const [center, setCenter] = useState<{ lng: number; lat: number }>({ lng: 116.404, lat: 39.915 });
  const [showMap, setShowMap] = useState<boolean>(false);
  const [markerPosition, setMarkerPosition] = useState<{ lng: number; lat: number } | null>(null);
  const [selectedEnergySources, setSelectedEnergySources] = useState({
    photovoltaic: false,
    chargingPile: false,
    windPower: false,
    oilPower: false,
    load: false,
  });
  const intl = useIntl();
  const handleSelectPoint = (locationPoint: { point: { lng: number; lat: number } }) => {
    setCenter(locationPoint.point);
    const pointString = `${locationPoint.point.lng}, ${locationPoint.point.lat}`;
    formRef.current?.setFieldsValue({
      point: pointString,
    });
  };

  const toggleMap = () => {
    setShowMap(!showMap);
  };

  useEffect(() => {
    if (detailInfo && detailInfo.energyComplex) {
      setSelectedEnergySources({
        photovoltaic: detailInfo.energyComplex.photovoltaicCapacity !== null,
        chargingPile: detailInfo.energyComplex.chargingPointCapacity !== null,
        windPower: detailInfo.energyComplex.windPowerCapacity !== null,
        oilPower: detailInfo.energyComplex.oilPowerCapacity !== null,
        load: detailInfo.energyComplex.loadCapacity !== null,
      });
    }
  }, [detailInfo]);

  const handleEnergySourcesChange = (checkedValues: string[]) => {
    const newSelected = {
      photovoltaic: checkedValues.includes(intl.formatMessage({ id: 'siteManage.pVPower' })),
      chargingPile: checkedValues.includes(intl.formatMessage({ id: 'siteManage.chargingPile' })),
      windPower: checkedValues.includes(intl.formatMessage({ id: 'siteManage.windPower' })),
      oilPower: checkedValues.includes(intl.formatMessage({ id: 'siteManage.dieselPower' })),
      load: checkedValues.includes(intl.formatMessage({ id: 'siteManage.load' })),
    };
    setSelectedEnergySources(newSelected);
  };

  const [form] = ProForm.useForm();
  useEffect(() => {
    if (detailInfo) {
      form.setFieldsValue({
        energyComplex: {
          photovoltaicCapacityUnit: detailInfo.energyComplex?.photovoltaicCapacityUnit || 'kWp',
          chargingPointCapacityUnit: detailInfo.energyComplex?.chargingPointCapacityUnit || 'kW',
          windPowerCapacityUnit: detailInfo.energyComplex?.windPowerCapacityUnit || 'kW',
          oilPowerCapacityUnit: detailInfo.energyComplex?.oilPowerCapacityUnit || 'kW',
          loadCapacityUnit: detailInfo.energyComplex?.loadCapacityUnit || 'kW',
          photovoltaicMode: detailInfo.energyComplex?.photovoltaicMode?.toString(),
        },
      });
    }
  }, [detailInfo, form]);
  return (
    <ProForm
      style={{ marginTop: 10 }}
      layout="horizontal"
      labelCol={{ flex: `${LABEL_WIDTH}px` }}
      formRef={formRef}
      form={form}
      submitter={{
        render:
          !disableEdit &&
          ((props, doms) => (
            <div style={{ paddingLeft: LABEL_WIDTH }}>
              <Space>{doms}</Space>
            </div>
          )),
      }}
      onFinish={async (value) => {
        console.log('Form submitted with values:', value);
        if (value.minSoc < 0 || value.maxSoc < 0) {
          message.error(intl.formatMessage({ id: 'global.SOCLimit' }));
          return;
        }
        if (value.minSoc > value.maxSoc) {
          message.error(intl.formatMessage({ id: 'global.SOCUpper' }));
          return;
        }
        let point = null;
        if (value.point) {
          const pointParts = value.point.split(',').map((part: string) => parseFloat(part.trim()));
          point = { lng: pointParts[0], lat: pointParts[1] };
        }

        const payload = {
          ...detailInfo,
          ...value,
          energyComplex: value.energyComplex,
        };

        if (point) {
          payload.point = point;
        }

        const res = await edit(payload as API.StationBaseReq);
        if (res.success) {
          message.success(intl.formatMessage({ id: 'global.modifiedSuccess' }));
        }
      }}
      disabled={disableEdit}
    >
      <Flex gap={40}>
        <div style={{ width: WIDTH }}>
          <ProFormDatePicker
            name="startRunTime"
            label={intl.formatMessage({ id: 'siteManage.operationTime' })}
            width={WIDTH - LABEL_WIDTH}
            rules={[
              {
                required: true,
                message: intl.formatMessage({ id: 'siteManage.plantTimeRequired' }),
              },
            ]}
          />
          <Flex gap={GAP}>
            <div style={{ width: WIDTH - 110 }}>
              <ProFormDigit
                name="ratedPower"
                label={intl.formatMessage({ id: 'siteManage.ratedPower' })}
                fieldProps={{
                  precision: 4,
                  max: 1000000000,
                }}
                rules={[
                  {
                    required: true,
                    message: intl.formatMessage({ id: 'siteManage.ratedPowerRequired' }),
                  },
                ]}
              />
            </div>
            <ProFormSelect
              width={100}
              valueEnum={POWER_UNIT}
              name="ratedPowerUnit"
              params={undefined}
              debounceTime={undefined}
              request={undefined}
            />
          </Flex>
          <ProFormDigit
            name="chargeDischargeCount"
            label={intl.formatMessage({ id: 'siteManage.maximumTime' })}
            fieldProps={{
              addonAfter: intl.formatMessage({ id: 'siteManage.number' }),
              precision: 0,
              min: 1,
              max: 1000000000,
            }}
            rules={[
              {
                required: true,
                message: intl.formatMessage({ id: 'siteManage.maximumChargeRequired' }),
              },
            ]}
          />
          <ProFormText
            name="cellTempNo"
            label={intl.formatMessage({ id: 'siteManage.cellCode' })}
            rules={[
              {
                required: true,
                message: intl.formatMessage({ id: 'siteManage.temperatureRequired' }),
              },
            ]}
            fieldProps={{
              maxLength: 30,
            }}
          />
          <ProFormText
            name="product"
            label={intl.formatMessage({ id: 'siteManage.batteryBrand' })}
            rules={[
              {
                required: true,
                message: intl.formatMessage({ id: 'siteManage.brandRequired' }),
              },
            ]}
            fieldProps={{
              maxLength: 30,
            }}
          />

          <ProFormDigit
            name="zycCount"
            label={intl.formatMessage({ id: 'siteManage.tanksNumber' })}
            rules={[
              {
                required: true,
                message: intl.formatMessage({ id: 'siteManage.mediumRequired' }),
              },
            ]}
            fieldProps={{
              min: 0,
              max: 99999,
            }}
          />
          <ProFormText
            name="address"
            label={intl.formatMessage({ id: 'siteManage.plantAddress' })}
            fieldProps={{
              maxLength: 200,
            }}
            rules={[
              {
                required: true,
                message: intl.formatMessage({ id: 'siteManage.addressRequired' }),
              },
            ]}
          />
          <ProFormRadio.Group
            label={intl.formatMessage({ id: 'electricityPrice.electricityPriceType' })}
            name="priceType"
            valueEnum={getSystemElectricityPriceType()}
            rules={[
              {
                required: true,
                message: `${intl.formatMessage({
                  id: 'electricityPrice.electricityPriceType',
                })}${intl.formatMessage({
                  id: 'global.cannotBeEmpty',
                })}`,
              },
            ]}
          />
        </div>
        <div style={{ width: WIDTH }}>
          <Flex gap={GAP}>
            <div style={{ width: WIDTH - 110 }}>
              <ProFormDigit
                name="capacity"
                label={intl.formatMessage({ id: 'siteManage.plantCapacity' })}
                rules={[
                  {
                    required: true,
                    message: intl.formatMessage({ id: 'siteManage.capacityRequired' }),
                  },
                ]}
              />
            </div>
            <ProFormSelect
              width={100}
              valueEnum={CAPACITY_UNIT}
              name="capacityUnit"
              params={undefined}
              debounceTime={undefined}
              request={undefined}
            />
          </Flex>
          <Flex gap={GAP}>
            <div style={{ width: WIDTH - 110 }}>
              <ProFormDigit
                name="chargeDischargeTime"
                label={intl.formatMessage({ id: 'siteManage.chargeDuration' })}
                fieldProps={{
                  precision: 4,
                  max: 1000000000,
                }}
                rules={[
                  {
                    required: true,
                    message: intl.formatMessage({ id: 'siteManage.durationRequired' }),
                  },
                ]}
              />
            </div>
            <ProFormSelect
              width={100}
              valueEnum={{
                H: {
                  text: intl.formatMessage({ id: 'remoteUpgradeMangment.versionManagement.hour' }),
                },
                M: {
                  text: intl.formatMessage({
                    id: 'remoteUpgradeMangment.versionManagement.minutes',
                  }),
                },
              }}
              name="chargeDischargeUnit"
              params={undefined}
              debounceTime={undefined}
              request={undefined}
            />
          </Flex>
          <Flex gap={GAP}>
            <div style={{ width: (WIDTH - LABEL_WIDTH - 30) / 2 + LABEL_WIDTH }}>
              <ProFormDigit
                name="batteryType1"
                label={intl.formatMessage({ id: 'siteManage.batteryType' })}
                fieldProps={{
                  addonAfter: 'C',
                  precision: 2,
                  min: 0.01,
                  max: 1000000000,
                }}
                tooltip={intl.formatMessage({ id: 'global.numbersOlny' })}
                rules={[
                  {
                    required: true,
                    message: intl.formatMessage({ id: 'siteManage.cdRequired' }),
                  },
                ]}
              />
            </div>
            <span style={{ fontSize: 20 }}>-</span>
            <div style={{ width: (WIDTH - LABEL_WIDTH - 30) / 2 }}>
              <ProFormDigit
                name="batteryType2"
                fieldProps={{
                  addonAfter: 'Ah',
                  precision: 0,
                  min: 1,
                  max: 1000000000,
                }}
                rules={[
                  {
                    required: true,
                    message: intl.formatMessage({ id: 'siteManage.batteryRequired' }),
                  },
                ]}
              />
            </div>
          </Flex>
          <ProFormDigit
            name="clusterRatedCapacity"
            label={intl.formatMessage({ id: 'siteManage.clusterAh' })}
            fieldProps={{
              addonAfter: 'Ah',
              min: 0,
              max: 1000000000,
            }}
            rules={[
              {
                required: true,
                message: intl.formatMessage({ id: 'siteManage.clusterRequired' }),
              },
              () => ({
                // @ts-ignore
                validator(_, value) {
                  if (value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(intl.formatMessage({ id: 'global.thanZero' }));
                },
              }),
            ]}
          />
          <ProFormDigit
            name="minSoc"
            label={intl.formatMessage({ id: 'siteManage.socLower' })}
            fieldProps={{ addonAfter: '%' }}
            min={0}
            max={100}
            rules={[
              {
                required: true,
                message: intl.formatMessage({ id: 'siteManage.socLowerRequired' }),
              },
            ]}
          />
          <ProFormDigit
            name="maxSoc"
            label={intl.formatMessage({ id: 'siteManage.socLimit' })}
            fieldProps={{ addonAfter: '%' }}
            min={0}
            max={100}
            rules={[
              {
                required: true,
                message: intl.formatMessage({ id: 'siteManage.socRequired' }),
              },
            ]}
          />
          <ProFormText
            label={intl.formatMessage({ id: 'siteManage.plantLocation' })}
            name="point"
            rules={[
              {
                required: false,
                message: intl.formatMessage({ id: 'siteManage.locationRequired' }),
              },
            ]}
            fieldProps={{
              placeholder: intl.formatMessage({ id: 'siteManage.selectPlease' }),
              addonAfter: (
                <Button
                  type="link"
                  shape="circle"
                  className={Styles.locationButton}
                  onClick={toggleMap}
                >
                  {intl.formatMessage({ id: 'siteManage.selectLocation' })}
                </Button>
              ),
            }}
            disabled
          />
          {showMap && (
            <MapComponent
              center={center}
              onSelectPoint={handleSelectPoint}
              markerPosition={markerPosition}
              setMarkerPosition={setMarkerPosition}
            />
          )}
        </div>
      </Flex>
      {/* 电池能源组成 */}
      {detailInfo?.stationType === '2' || detailInfo?.stationType === '6' ? (
        <div style={{ marginTop: 20 }}>
          <Title level={4}>{intl.formatMessage({ id: 'siteManage.batteryComposition' })}</Title>
          <Flex gap={GAP}>
            <div style={{ width: WIDTH - 300 }}></div>
            <ProFormCheckbox.Group
              name="energySources"
              options={[
                intl.formatMessage({ id: 'siteManage.pVPower' }),
                intl.formatMessage({ id: 'siteManage.chargingPile' }),
                intl.formatMessage({ id: 'siteManage.windPower' }),
                intl.formatMessage({ id: 'siteManage.dieselPower' }),
                intl.formatMessage({ id: 'siteManage.load' }),
              ]}
              // @ts-ignore
              onChange={handleEnergySourcesChange}
              value={Object.keys(selectedEnergySources)
                .filter((key) => selectedEnergySources[key as keyof typeof selectedEnergySources])
                .map((key) => {
                  if (key === 'photovoltaic')
                    return intl.formatMessage({ id: 'siteManage.pVPower' });
                  if (key === 'chargingPile')
                    return intl.formatMessage({ id: 'siteManage.chargingPile' });
                  if (key === 'windPower')
                    return intl.formatMessage({ id: 'siteManage.windPower' });
                  if (key === 'oilPower')
                    return intl.formatMessage({ id: 'siteManage.dieselPower' });
                  if (key === 'load') return intl.formatMessage({ id: 'siteManage.load' });
                  return '';
                })}
            />
          </Flex>
          {selectedEnergySources.photovoltaic && (
            <Flex gap={40}>
              <Flex gap={GAP}>
                <div style={{ width: WIDTH - 110 }}>
                  <ProFormDigit
                    name={['energyComplex', 'photovoltaicCapacity']}
                    label={intl.formatMessage({ id: 'siteManage.pVCapacity' })}
                    min={0.01}
                    max={10000}
                    rules={[
                      {
                        required: true,
                        message: intl.formatMessage({ id: 'siteManage.enterPlease' }),
                      },
                    ]}
                  />
                </div>
                <ProFormSelect
                  width={100}
                  valueEnum={PHO_UNIT}
                  name={['energyComplex', 'photovoltaicCapacityUnit']}
                />
              </Flex>
              <div style={{ width: WIDTH }}>
                <ProFormSelect
                  label={intl.formatMessage({
                    id: 'electricityPrice.photovoltaicGridConnectedMode',
                  })}
                  valueEnum={getPvGridConnectedMode()}
                  name={['energyComplex', 'photovoltaicMode']}
                  rules={[
                    {
                      required: true,
                      message: intl.formatMessage({ id: 'siteManage.enterPlease' }),
                    },
                  ]}
                />
              </div>
            </Flex>
          )}
          {selectedEnergySources.chargingPile && (
            <Flex gap={GAP}>
              <div style={{ width: WIDTH - 110 }}>
                <ProFormDigit
                  name={['energyComplex', 'chargingPointCapacity']}
                  label={intl.formatMessage({ id: 'siteManage.pileCapacity' })}
                  min={0.01}
                  max={10000}
                  rules={[
                    {
                      required: true,
                      message: intl.formatMessage({ id: 'siteManage.enterPlease' }),
                    },
                  ]}
                />
              </div>
              <ProFormSelect
                width={100}
                valueEnum={PIE_UNIT}
                name={['energyComplex', 'chargingPointCapacityUnit']}
              />
            </Flex>
          )}
          {selectedEnergySources.windPower && (
            <Flex gap={GAP}>
              <div style={{ width: WIDTH - 110 }}>
                <ProFormDigit
                  name={['energyComplex', 'windPowerCapacity']}
                  label={intl.formatMessage({ id: 'siteManage.windCapacity' })}
                  min={0.01}
                  max={10000}
                  rules={[
                    {
                      required: true,
                      message: intl.formatMessage({ id: 'siteManage.enterPlease' }),
                    },
                  ]}
                />
              </div>
              <ProFormSelect
                width={100}
                valueEnum={POWER_UNIT}
                name={['energyComplex', 'windPowerCapacityUnit']}
              />
            </Flex>
          )}
          {selectedEnergySources.oilPower && (
            <Flex gap={GAP}>
              <div style={{ width: WIDTH - 110 }}>
                <ProFormDigit
                  name={['energyComplex', 'oilPowerCapacity']}
                  label={intl.formatMessage({ id: 'siteManage.dieselCapacity' })}
                  min={0.01}
                  max={10000}
                  rules={[
                    {
                      required: true,
                      message: intl.formatMessage({ id: 'siteManage.enterPlease' }),
                    },
                  ]}
                />
              </div>
              <ProFormSelect
                width={100}
                valueEnum={POWER_UNIT}
                name={['energyComplex', 'oilPowerCapacityUnit']}
              />
            </Flex>
          )}
          {selectedEnergySources.load && (
            <Flex gap={GAP}>
              <div style={{ width: WIDTH - 110 }}>
                <ProFormDigit
                  name={['energyComplex', 'loadCapacity']}
                  label={intl.formatMessage({ id: 'siteManage.loadCapacity' })}
                  min={0.01}
                  max={10000}
                  rules={[
                    {
                      required: true,
                      message: intl.formatMessage({ id: 'siteManage.enterPlease' }),
                    },
                  ]}
                />
              </div>
              <ProFormSelect
                width={100}
                valueEnum={POWER_UNIT}
                name={['energyComplex', 'loadCapacityUnit']}
              />
            </Flex>
          )}
        </div>
      ) : (
        ''
      )}
    </ProForm>
  );
};

const ParamConfig: React.FC<{
  detailInfo: API.StationInfo;
  id: string | number;
  className?: string;
  disableEdit?: boolean;
}> = ({ detailInfo, id, disableEdit }) => {
  const access = useAccess();
  const electricityPriceRef = useRef(null);
  const deviceRef = useRef(null);
  const intl = useIntl();
  let items: TabsProps['items'] = [];

  const tab1 = {
    key: '1',
    label: intl.formatMessage({ id: 'siteManage.basicParameters' }),
    children: <BaseParam detailInfo={detailInfo} disableEdit={disableEdit} />,
  };

  const tab2 = {
    key: '2',
    label: '电价参数',
    children: <ElectricityPrice ref={electricityPriceRef} id={id} disableEdit={disableEdit} />,
  };

  const tab3 = {
    key: '3',
    label: intl.formatMessage({ id: 'siteManage.temperatureCollection' }),
    children: <TempCollectePoint id={id as string} disableEdit={disableEdit} />,
  };

  const tab4 = {
    key: '4',
    label: '设备信息',
    children: <Device ref={deviceRef} id={id} disableEdit={disableEdit} />,
  };

  if (disableEdit) {
    items = [tab1, tab2, tab3, tab4];
  } else {
    if (access.can('sys:station:paramConf:base')) {
      items.push(tab1);
    }
    if (access.can('sys:station:paramConf:TempColPoint')) {
      items.push(tab3);
    }
  }

  const [activeKey, setActiveKey] = useState(items?.[0]?.key);

  const onChange = (key: string) => {
    setActiveKey(key);
  };

  return (
    <Tabs
      activeKey={activeKey}
      items={items}
      onChange={onChange}
      tabBarExtraContent={
        (activeKey === '2' && !disableEdit && <ToolBarRender tableRef={electricityPriceRef} />) ||
        (activeKey === '4' && !disableEdit && <DeviceToolBarRender tableRef={deviceRef} />)
      }
      tabsLevel={2}
    />
  );
};

export default ParamConfig;
